﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Trackr.Core;
using Trackr.Core.Entities;
using Trackr.GUI.Extensions;
using Trackr.GUI.ViewModels;

namespace Trackr.GUI.Views
{
	/// <summary>
	/// Interaction logic for MainWindow.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		//private System.Timers.Timer _timer;
		public MainWindow()
		{
			//start with windows
			bool autoStart = Core.ConfigUtility.Instance["autostart"].ParseDefault(false);
			Core.RegistryUtility.AutoStart(autoStart, System.Reflection.Assembly.GetExecutingAssembly().Location);

			InitializeComponent();
			InitializeTrayIcon();
			InitializeTimer();
			InitializeDragEvents();

            AddHandler(Keyboard.KeyDownEvent, (KeyEventHandler)HandleKeyDownEvent);
		}

        private void HandleKeyDownEvent(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.C && Keyboard.Modifiers.HasFlag(ModifierKeys.Control)){
                MessageBox.Show("CTRL + C trapped");
            }
        }
		
        private void InitializeTrayIcon()
		{
			var hideMenuItem = CreateMenuItem("Hide", () => { this.FadeOut(); });
			var openMenuItem = CreateMenuItem("Open", () => { this.FadeIn(); });
			var exitMenuItem = CreateMenuItem("Exit", () => { this.Close(); });
			var notifyIcon = new System.Windows.Forms.NotifyIcon();
			using (var iconStream = Application.GetResourceStream(new Uri("pack://application:,,,/Trackr.GUI;component/Views/Images/time.ico")).Stream)
			{
				notifyIcon.Icon = new System.Drawing.Icon(iconStream);
			}
			notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(new[] { hideMenuItem, openMenuItem, exitMenuItem });
			notifyIcon.Visible = true;
			notifyIcon.DoubleClick += (sender, e) =>
			{
				this.FadeIn();
			};
		}

		private System.Windows.Forms.MenuItem CreateMenuItem(string name, Action clickDelegate)
		{
			return new System.Windows.Forms.MenuItem(name, (o, e) =>
			{
				clickDelegate();
			});
		}

		private void InitializeDragEvents()
		{
			gridHeader.MouseLeftButtonDown += (obj, e) => this.DragMove();
			imageClose.MouseLeftButtonDown += (sender, e) => this.FadeOut();
		}

		private void InitializeTimer()
		{
			//get our datacontext for the main window
			var ctxt = this.DataContext as MainWindowViewModel;
			if (ctxt == null)
				return;

			//get interval and timeout values from config appData
			int intervalMinutes = Core.ConfigUtility.Instance["interval"].ParseDefault(30);
			int timeOutMinutes = Core.ConfigUtility.Instance["timeout"].ParseDefault(2);

			//setup timers
			var timer = new System.Timers.Timer(TimeSpan.FromMinutes(intervalMinutes).TotalMilliseconds);
			var timeOut = new System.Timers.Timer(TimeSpan.FromMinutes(timeOutMinutes).TotalMilliseconds);

			//when the timeout timer has elapsed the user has not entered any info so we need to stop the the current Model.TimeItem
			timeOut.Elapsed += (sender, eventArgs) =>
			{
				ctxt.StopCurrent();
				this.Invoke(() =>
				{
					//change the color to notify that something happend
					BorderMain.Background = new LinearGradientBrush(Colors.OrangeRed, Colors.DarkOrange, 90.0);
					inputTask.Focus();
				});
			};

			//when the timer has elapsed show the form and start the timeout timer
			timer.Elapsed += (obj, e) =>
			{
				this.FadeIn();
				timer.Stop();
				timeOut.Start();
			};

			//when a task has been submitted start the timer, stop the timeout and hide the window
			ctxt.TaskSubmitted += (Trackr.Model.TimeItem, e) =>
			{
				this.FadeOut();
				timer.Start();
				timeOut.Stop();
				this.Invoke(() =>
				{
					BorderMain.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF4B95D8"));
				});
			};

		}
	}
}
